import React, { useRef, useEffect } from "react";
import styles from "./index.module.css";

export default function Sticky({ height, children }) {
  // 监听 scroll 事件
  const placeholderRef = useRef(null);
  const contentRef = useRef(null);
  useEffect(() => {
    const handleScroll = () => {
      if (placeholderRef.current === null) return;
      const { top } = placeholderRef.current.getBoundingClientRect();
      if (top < 0) {
        //吸顶
        contentRef.current.classList.add(styles.fixed);
        placeholderRef.current.style.height = `${height}px`;
      } else {
        contentRef.current.classList.remove(styles.fixed);
        placeholderRef.current.style.height = "0px";
      }
    };
    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, [height]);

  return (
    <div>
      {/* 占位元素 */}
      <div ref={placeholderRef} />
      {/* 内容元素 */}
      <div ref={contentRef}>{children}</div>
    </div>
  );
}
